import type { HookFetchPlugin } from 'hook-fetch';
import { ElMessage } from 'element-plus';
import hookFetch from 'hook-fetch';
import { sseTextDecoderPlugin } from 'hook-fetch/plugins';
import router from '@/routers';
import { safeGetUserStore } from './storeUtils';

// 请求配置接口
interface RequestConfig {
  url: string;
  baseURL: string;
  params: Record<string, any>;
  data?: Record<string, any>;
  withCredentials: boolean;
  method: string;
  headers: Record<string, any>;
  qsArrayFormat: string;
}

// 响应结果接口
interface ResponseResult<T = any> {
  code: number;
  msg: string;
  data?: T;
  rows?: T[];
}

// 完整响应接口
interface BaseResponse<T = any> {
  config: RequestConfig;
  response: Record<string, any>;
  responseType: string;
  controller: Record<string, any>;
  result: ResponseResult<T>;
}

export const request = hookFetch.create<BaseResponse>({
  baseURL: import.meta.env.VITE_API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  plugins: [sseTextDecoderPlugin({ json: true, prefix: 'data:' })],
});

function jwtPlugin(): HookFetchPlugin<BaseResponse> {
  return {
    name: 'jwt',
    beforeRequest: async (config) => {
      const userStore = await safeGetUserStore();

      config.headers = new Headers(config.headers);
      if (userStore?.token) {
        config.headers.set('authorization', `Bearer ${userStore.token}`);
        config.headers.set('token', userStore.token);
      }
      config.data && ((config.data as any)['_t'] = new Date().getTime())
      return config;
    },
    afterResponse: async (response) => {
      // console.log(response);
      // 根据实际响应，成功的状态码是 0 或 200
      if (response.result?.code === 0 || response.result?.code === 200) {
        return response;
      }

      // 处理403逻辑
      if (response.result?.code === 403) {
        // 跳转到403页面（确保路由已配置）
        router.replace({
          name: '403',
        });
        ElMessage.error(response.result?.msg || '无权限访问');
        return Promise.reject(response);
      }

      // 处理401逻辑
      if (response.result?.code === 401) {
        const userStore = await safeGetUserStore();
        if (userStore) {
          // 如果没有权限，退出，且弹框提示登录
          userStore.logout();
          userStore.openLoginDialog();
        }
      }

      ElMessage.error(response.result?.msg || '请求失败');
      return Promise.reject(response);
    },
  };
}

request.use(jwtPlugin());

// 导出类型
export type {
  RequestConfig,
  ResponseResult,
  BaseResponse,
  LoginResponseData,
  MenuResponseData,
  PermissionResponseData,
  DictResponseData,
  AgentResponseData,
};

export const post = request.post;

export const get = request.get;

export const put = request.put;
